let currentAudio: any = null;
import useToast from './useToast';
const { showToast } = useToast();
export default function usePlayAudio() {
  const isPlaying = ref(false);
  const playAudio = (newAudioSrc: string) => {
    // 如果当前有音频在播放，停止它
    if (!newAudioSrc) {
      showToast('暂无音频可播放');
      return false;
    }
    if (currentAudio) {
      currentAudio.stop();
      isPlaying.value = false;
    }

    // 创建新的音频对象
    currentAudio = uni.createInnerAudioContext();
    currentAudio.src = newAudioSrc;

    // 播放音频
    currentAudio.play();
    isPlaying.value = true;

    // 监听播放结束事件
    currentAudio.onEnded(() => {
      isPlaying.value = false;
      currentAudio = null;
    });

    // 监听播放错误事件
    currentAudio.onError((err: string) => {
      console.error('播放错误:', err);
      showToast('播放错误');
      isPlaying.value = false;
      currentAudio = null;
    });
  };
  // 暴露停止播放的功能，以便在组件销毁时调用
  const stopAudio = () => {
    if (currentAudio) {
      currentAudio.stop();
      isPlaying.value = false;
      currentAudio = null;
    }
  };
  return { isPlaying, playAudio, stopAudio };
}
